package server;

import java.net.*;
import java.io.*;

/**********************************************************************
*
* Filename: Server_TCP_Connection.java
*
* File Description:
* Class to handle the server side of the TCP connection
*
* Author:
* @author Tim Schmalz
* Date Created:
*  Oct 9, 2009
*
**********************************************************************/
public class Server_TCP_Connection
{
	private ServerSocket serverSocket;
	private final int DEFAULT_PORT = 1129;

        /**
         * Opens a new port at the default port (1129)
         *
         * @throws IOException
         */
	public Server_TCP_Connection() throws IOException
	{
		serverSocket = openSocket(DEFAULT_PORT);
	}

        /**
         * Opens a new port at the given port value
         *
         * @param port - Port to open
         * @throws IOException
         */
	public Server_TCP_Connection(int port) throws IOException
	{
		serverSocket = openSocket(port);
	}

        /**
         * Opens a socket at the given port
         *
         * @param port - port to open
         * @return Opened ServerSocket
         * @throws IOException
         */
	private ServerSocket openSocket(int port) throws IOException
	{
		ServerSocket serverSocket = null;
		try
		{
			serverSocket = new ServerSocket(port);
		}
		catch(IOException ioe)
		{
			System.err.println("Could not listen on port: " + port);
			throw new IOException("Could not listen on port " + port);
		}
		return serverSocket;
	}

        /**
         * Closes current socket
         *
         * @throws IOException
         */
        public void closeSocket() throws IOException
        {
            serverSocket.close();
        }

        /**
         * Returns the server socket
         *
         * @return ServerSocket in use
         */
	public ServerSocket getSocket()
	{
		return serverSocket;
	}

        /**
         * Waits for clients and gives the a thread to run
         *
         * @return The users socket
         * @throws IOException
         */
	public Socket waitForClients() throws IOException
	{
		Socket clientSocket = null;
		try
		{
                    clientSocket = serverSocket.accept();
                }
                catch(SocketException socke)
                {
                    if(Draft_Server.isRunning == true)
                    {
                        System.out.println("Accept has recieved a socket error");
                    }
                }
		catch(IOException ioe)
		{
                    System.err.println("Client Acceptance Failed");
                    throw new IOException("Client Acceptance Failed");
		}
		return clientSocket;
	}
}